package cz.zcu.fav.ratdroid.adapter;

import java.util.HashMap;
import java.util.List;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;
import cz.zcu.fav.ratdroid.R;
import cz.zcu.fav.ratdroid.bean.Period;

public class PeriodsCheckboxArrayAdapter extends ArrayAdapter<Period> implements
		OnClickListener
{
	private final Context context;

	// store CheckTextView's
	private HashMap<Period, CheckedTextView> checkedList = new HashMap<Period, CheckedTextView>();
	private DateTimeFormatter  dateFormat;
	// store state
	private HashMap<Period, Boolean> isChecked = new HashMap<Period, Boolean>();

	// list of periods
	// private List<Period> periods;

	public PeriodsCheckboxArrayAdapter(Context context, int textViewResourceId,
			List<Period> periods)
	{
		super(context, textViewResourceId, periods);
		this.context = context;
		dateFormat = DateTimeFormat.fullDateTime().withLocale(context.getResources().getConfiguration().locale);
	}
	
	public PeriodsCheckboxArrayAdapter(Context context, int textViewResourceId,
			List<Period> periods, HashMap<Period, Boolean> isChecked)
	{
		this(context, textViewResourceId, periods);
		this.isChecked = isChecked;
	}

	public HashMap<Period, Boolean> getItems() {
		return isChecked;
	}
	
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View v = convertView;
		if (v == null)
		{
			LayoutInflater vi = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.period_row, null);
		}

		Period per = getItem(position);
		if (per.getId() != null)
		{
			((TextView) v).setText(dateFormat.print(per.getFromDate()) + " - " + dateFormat.print(per.getToDate()));
		}

		CheckedTextView checkedTextView = (CheckedTextView) v;

		if (!isChecked.containsKey(getItem(position)))
		{
			isChecked.put(getItem(position), getItem(position).isValid());
		}
		checkedTextView.setChecked(isChecked.get(getItem(position)));
		
		checkedList.put(getItem(position), (CheckedTextView) v);
		v.setTag(getItem(position));
		v.setOnClickListener(this);
		return v;
	}

	public void onClick(View v)
	{
		CheckedTextView ct = checkedList.get(v.getTag());
		ct.toggle();

		isChecked.put((Period)ct.getTag(), ct.isChecked());

	}

}
